package com.dai.rpc.netty.task;

import com.dai.rpc.config.MyRpcConfig;
import com.dai.rpc.message.RpcRequest;
import com.dai.rpc.register.zookeeper.ZKServiceDiscovery;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 执行定时任务，从zookeeper中获取实例并缓存
 */
@Slf4j
public class UpdateServiceTask implements TimerTask {

    private Set<String> services;
    private ZKServiceDiscovery zkServiceDiscovery;
    private RpcRequest rpcRequest;

    public UpdateServiceTask(Set<String> services, ZKServiceDiscovery zkServiceDiscovery, RpcRequest rpcRequest) {
        this.services = services;
        this.zkServiceDiscovery = zkServiceDiscovery;
        this.rpcRequest = rpcRequest;
    }

    @Override
    public void run(Timeout timeout) throws Exception {

        InetSocketAddress inetAddress = zkServiceDiscovery.lookupService(rpcRequest);
        log.info("定时任务获取到了新的实例：{}",inetAddress.toString());
        // 缓存实例
        String ipPort = inetAddress.getHostName() + "," + inetAddress.getPort();
        services.add(ipPort);
        timeout.timer().newTimeout(this,10, TimeUnit.SECONDS);

    }
}
